<?php

namespace app\admin\model;

use think\Model;

class SpecArt extends Model
{
    protected $autoWriteTimestamp = 'datetime';
    protected $createTime = 'update_time';

    protected static function init()
    {
        //插入之前放图片
        SpecArt::event('before_insert',function($spec_art){
            if($_FILES['thumb']['tmp_name']){
                $file = request()->file('thumb');
                $info = $file->validate(['ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads'.'/'.'spec');
                if($info){
                    // $thumb=ROOT_PATH . 'public' . DS . 'uploads'.'/'.$info->getExtension();
                    $filePath=DS .'uploads'.'/'.'spec'.'/'.$info->getSaveName();
                    $thumb = str_replace("\\", "/", $filePath);
                    $spec_art['thumb']=$thumb;
                }
            }
        });

        //修改数据之前先修改图片路劲并删除图片
        SpecArt::event('before_update', function ($spec_art) {
            $file = request()->file('thumb');
            if (!empty($file)) {
                $arts = SpecArt::find($spec_art->id);
                $thumbpath = $_SERVER['DOCUMENT_ROOT'].$arts['thumb'];
                if (file_exists($thumbpath)) {
                    @unlink($thumbpath);
                }
                $file = request()->file('thumb');
                $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads'.'/'.'spec');
                if ($info) {
                    $filePath=DS .'uploads'.'/'.'spec'.'/'.$info->getSaveName();
                    $thumb = str_replace("\\", "/", $filePath);
                    $spec_art['thumb']=$thumb;
                }
            }
        });

        //删除数据之前先删除缩略图
        SpecArt::event('before_delete', function ($spec_art) {
            $arts = Article::find($spec_art->id);
            $thumbpath = $_SERVER['DOCUMENT_ROOT'].$arts['thumb'];
            if (file_exists($thumbpath)) {
                @unlink($thumbpath);
            }
        });
    }
}
